import AxiosInstance from './axios'
const runjsonField = 'rjbody'

class HttpRequest {
  constructor() {
    this.instance = new AxiosInstance()
  }

  /**
   * 生成地址
   * @param {String} service api 名称
   * @param {Object} args 参数
   */
  url = (service, args) => {
    const body = {
      service: service
    }
    if (args) {
      body['args'] = args
    }
    const query = JSON.stringify([body])
    return process.env.API_URL + '?' + query
  }

  /**
  * get 请求
  * @param {Object} data
  * @param {Boolean} autoProcessRJError
  * @param {Object} extOpt 其它 header 属性
  */
  get = (page, data, autoProcessRJError, extOpt) => {
    const opt = Object.assign(extOpt || {}, {
      method: 'get',
      url: process.env.API_URL,
      data
    })
    return new AxiosInstance(page).request(opt, autoProcessRJError)
  }

  /**
   * post 请求
   * @param {*} data
   * @param {*} autoProcessRJError
   * @param {Object} extOpt 其它 header 属性
   */
  post = (page, data, autoProcessRJError, extOpt) => {
    // const opt = {
    //   method: 'post',
    //   url: process.env.API_URL,
    //   data
    // }
    const opt = Object.assign(extOpt || {}, {
      method: 'post',
      url: process.env.API_URL,
      data
    })
    return new AxiosInstance(page).request(opt, autoProcessRJError)
  }

  download = (page, data, extOpt, cancelHandle) => {
    const opt = Object.assign(extOpt || {}, {
      url: process.env.API_URL
    })
    return new AxiosInstance(page).download(data, opt, cancelHandle)
  }

  /**
   * 上传文件
   * @param {String} service  接口 API
   * @param {Object} args     参数
   * @param {Array} files    要上传件的文件列表
   * @param {Boolean} autoProcessRJError，true 或不传值时起作用
   */
  upload = (page, data, files, autoProcessRJError) => {
    const formData = new FormData()
    for (var field in files) {
      formData.append(field, files[field])
    }
    formData.append(runjsonField, JSON.stringify(data))
    return this.post(page, formData, autoProcessRJError, {
      headers: {
        'Content-Type': 'multipart/form-data',
        '--run-json-field--': runjsonField
      }
    })
  }
}

const http = new HttpRequest()

export default http
